// 状态消息显示
function showStatus(message, type = 'info') {
    const statusDiv = document.getElementById('statusMessage');
    statusDiv.textContent = message;
    statusDiv.className = `status-message ${type}`;
    statusDiv.style.display = 'block';
    setTimeout(() => {
        statusDiv.style.display = 'none';
    }, 3000);
}

// 包列表折叠功能
function togglePackageList(venvName) {
    const section = document.querySelector(`#package-list-${venvName}`).closest('.package-section');
    section.classList.toggle('expanded');
}

// 安装包
function installPackage(venvName) {
    const input = document.getElementById(`package-input-${venvName}`);
    const package = input.value.trim();
    
    if (!package) {
        showStatus('请输入包名称', 'error');
        return;
    }
    
    fetch(`/venv/install_package/${venvName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `package=${encodeURIComponent(package)}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showStatus(data.error, 'error');
        } else {
            showStatus(data.message, 'success');
            setTimeout(() => window.location.reload(), 1000);
        }
    })
    .catch(error => {
        showStatus(`安装失败: ${error}`, 'error');
    });
}

// 卸载包
function uninstallPackage(venvName, packageName) {
    if (!confirm(`确定要卸载 ${packageName} 吗？`)) {
        return;
    }
    
    fetch(`/venv/uninstall_package/${venvName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `package=${encodeURIComponent(packageName)}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showStatus(data.error, 'error');
        } else {
            showStatus(data.message, 'success');
            setTimeout(() => window.location.reload(), 1000);
        }
    })
    .catch(error => {
        showStatus(`卸载失败: ${error}`, 'error');
    });
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 为包输入框添加回车键事件
    document.querySelectorAll('.package-input').forEach(input => {
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                const venvName = input.id.replace('package-input-', '');
                installPackage(venvName);
            }
        });
    });

    // 阻止包管理操作区域的点击事件冒泡
    document.querySelectorAll('.package-actions').forEach(actions => {
        actions.addEventListener('click', (e) => {
            e.stopPropagation();
        });
    });
}); 